/**
 * 交换元素的问题：每次交换元素都会进行三次操作
 * 简单优化：可以将当前元素保存起来，将需要交换位置的元素向后移动，最后进行一次赋值操作
 */
public class AlgoVisualizer2 {

    private InsertionSortData data;

    public AlgoVisualizer2(int randomBound, int N) {
        // 初始化数据
        data = new InsertionSortData(N, randomBound);
    }

    // 动画逻辑
    private void run() {
        for (int i = 0; i < data.N(); i ++) {
            int num = data.get(i);
            int j = i;
            for (; j > 0 && data.get(j - 1) > num; j --) {
                data.setData(j, data.get(j - 1));
            }
            data.setData(j, num);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        int randomBound = 800;
        int N = 100;

        AlgoVisualizer2 visualizer = new AlgoVisualizer2(randomBound, N);
        visualizer.run();
        Thread.sleep(2000);
        for (int i = 0; i < N; i ++) {
            System.out.print(visualizer.data.get(i) + " ");
        }
    }
}
